package com.sh.data.engine.job.admin.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.data.engine.job.admin.core.model.XxlJobUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author xuxueli 2019-05-04 16:44:59
 */
@Mapper
public interface XxlJobUserDao extends BaseMapper<XxlJobUser> {

    default List<XxlJobUser> pageList(int offset, int pagesize, String username, int role) {
        LambdaQueryWrapper<XxlJobUser> wrapper = new QueryWrapper<XxlJobUser>().lambda();
        wrapper
            .like(StringUtils.isNotBlank(username), XxlJobUser::getUsername, username)
            .eq(role > -1, XxlJobUser::getRole, role)
            .orderByAsc(XxlJobUser::getUsername);

        // .last(String.format("LIMIT %d,%d", offset, pagesize));
        Page<XxlJobUser> xxlJobUserPage = selectPage(new Page<XxlJobUser>(offset, pagesize), wrapper);
        return xxlJobUserPage.getRecords();
    }

    default int pageListCount(int offset, int pagesize, String username, int role) {
        LambdaQueryWrapper<XxlJobUser> wrapper = new QueryWrapper<XxlJobUser>().lambda();
        wrapper
            .like(StringUtils.isNotBlank(username), XxlJobUser::getUsername, username)
            .eq(role > -1, XxlJobUser::getRole, role);
        return Math.toIntExact(this.selectCount(wrapper));
    }

    default XxlJobUser loadByUserName(String username) {
        LambdaQueryWrapper<XxlJobUser> wrapper = new QueryWrapper<XxlJobUser>().lambda();
        wrapper.eq(XxlJobUser::getUsername, username);
        return this.selectOne(wrapper);
    }

    default int save(XxlJobUser xxlJobUser) {
        return this.insert(xxlJobUser);
    }

    default int update(XxlJobUser xxlJobUser) {
        LambdaUpdateWrapper<XxlJobUser> update = new UpdateWrapper<XxlJobUser>().lambda();
        update
            .eq(XxlJobUser::getId, xxlJobUser.getId())
            .set(XxlJobUser::getRole, xxlJobUser.getRole())
            .set(XxlJobUser::getPermission, xxlJobUser.getPermission())
            .set(
                StringUtils.isNotBlank(xxlJobUser.getPassword()),
                XxlJobUser::getPassword,
                xxlJobUser.getPassword());
        return this.update(null, update);
    }

    default int delete(int id) {
        return this.deleteById(id);
    }
}
